from os.path import dirname, basename

from webob import Response

from zope.component import queryUtility

from repoze.bfg.interfaces import ISettings
from repoze.bfg.path import caller_path

from mako.template import Template
from mako.lookup import TemplateLookup

def _filesystem_checks():
    settings = queryUtility(ISettings)
    filesystem_checks = (settings and settings.reload_templates) or False
    return filesystem_checks 
    

class BfgLoader(TemplateLookup):
    """ 
    Extends mako.lookup.TemplateLookup with configurable filesystem_checks    
    """
    def __init__(self, *args, **kwargs):
        super(BfgLoader, self).__init__(*args, **kwargs)
        self.filesystem_checks = _filesystem_checks()
        

def get_template(path, output_encoding=None,
        encoding_errors='strict'):
    """ Return a z3c.pt template object at the package-relative path
    (may also be absolute) """
    abspath = caller_path(path)
    loader = BfgLoader([dirname(abspath)])
    return loader.get_template(basename(path))

def render_template(path, output_encoding=None, encoding_errors='strict', 
        as_unicode=False, *args, **data):
    """ Render a z3c.pt (ZPT) template at the package-relative path
    (may also be absolute) using the kwargs in ``*kw`` as top-level
    names and return a string. """
    path = caller_path(path)
    template = get_template(path, output_encoding=output_encoding,
            encoding_errors=encoding_errors)
    if as_unicode:
        return template.render_unicode(*args, **data)
    else:
        return template.render(*args, **data)

def render_template_to_response(path, *args, **data):
    """ Render a z3c.pt (ZPT) template at the package-relative path
    (may also be absolute) using the kwargs in ``*kw`` as top-level
    names and return a Response object. """
    path = caller_path(path)
    result = render_template(path, *args, **data)
    return Response(result)

